﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using mmoss.orm;
using mmoss.application.classes;
using mmoss.tools;
using mmoss.configuration;
using System.Data.Linq;

namespace mmoss.application
{
    public partial class frmPatients : Form
    {
        private static int TABNUMBER = 3;
        //webcam
        mmoss.tools.webcamera.WebCam l_cam;
        private enum viewMode
        {
            VIEW,
            MODIFY,
            NEW,
            PREVIEW
        }
        private viewMode _viewMode;
        private string sLicense="";
        private bool isRunning = false;
        private Patient _currentPatient;
        public frmPatients()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmPatients_Load);
        }

        void frmPatients_Load(object sender, EventArgs e)
        {
            txtPatientBirthDate.Enter += new EventHandler(delegate(object s, EventArgs evt)
                {
                    txtPatientBirthDate.SelectAll();
                    txtPatientBirthDate.Focus();
                }
            );

            //set events for touch-screen events
            txtPatientFirstName.Enter += new EventHandler(txtItem_Enter);
            txtPatientLastName.Enter += new EventHandler(txtItem_Enter);
            txtPatientAddress1.Enter += new EventHandler(txtItem_Enter);
            txtPatientAddress2.Enter += new EventHandler(txtItem_Enter);
            txtPatientZip.Enter+= new EventHandler(txtItem_Enter);
            txtPatientCity.Enter+=new EventHandler(txtItem_Enter);
            txtEmailAddress.Enter+=new EventHandler(txtItem_Enter);

            //((frmContainer)this.MdiParent).keyStrokeMessageFilter
            timer1.Tick += new EventHandler(timer1_Tick);
            //set double click for files
            gvFiles.MouseDoubleClick += new MouseEventHandler(gvFiles_MouseDoubleClick);
            gvFiles.AutoGenerateColumns = false;
            //set the states
            cboState.DataSource = dbConn.db.LookupItems.Where(p => p.lookupTypeID == 1);
            cboState.DisplayMember = "lookupDesc";
            cboState.ValueMember = "lookupID";
            //set the file types
            cboFileType.DataSource = dbConn.db.FileTypes;
            cboFileType.DisplayMember = "fileTypeDesc";
            cboFileType.ValueMember = "fileTypeID";
            //set the filter for file browse - these will be used to figure out what type of file is uploaded
            openFileDialog1.Filter = "Red Card|*.*|Drivers License|*.*|Doctor Req|*.*|Application|*.*|Other|*.*";
            _viewMode = viewMode.VIEW;
            //chkMember.Click += new EventHandler(chkMember_Click);
            dgPatientList.CellClick += new DataGridViewCellEventHandler(dgPatientList_CellContentClick);
            dgPatientList.AutoGenerateColumns = false;
            //dgPatientList.RowEnter += new DataGridViewCellEventHandler(dgPatientList_CellContentClick);
            //dgPatientList.CellContentClick += new DataGridViewCellEventHandler(dgPatientList_CellContentClick);
            btnBrowse.Click+=new EventHandler(btnBrowse_Click);
            tbPatient1.SelectedIndexChanged += new EventHandler(tbPatient1_SelectedIndexChanged);
            txtLicenseInfo.KeyUp += new KeyEventHandler(txtLicenseInfo_KeyUp);
            txtPatientNameSearch.KeyDown += new KeyEventHandler(txtPatientNameSearch_KeyDown);
            txtPatientNameSearch.KeyUp += new KeyEventHandler(txtPatientNameSearch_KeyUp);
        }


        void txtItem_Enter(object sender, EventArgs e)
        {
            if (Default.TouchScreen)
            {
                frmTouchKeyboard l_keyboard = new frmTouchKeyboard();
                l_keyboard.MdiParent = this.MdiParent;
                l_keyboard.WindowState = FormWindowState.Maximized;
                l_keyboard.Show();
                l_keyboard.FormClosed += new FormClosedEventHandler(delegate(object s, FormClosedEventArgs ev)
                {
                    ((TextBox)sender).Text = ((frmTouchKeyboard)s).TypedString;
                }
                );
            }
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            //handles the output of the license window to parse patient data
            timer1.Enabled = false;
            timer1.Stop();
            //fill in data
            string[] l_items = txtLicenseInfo.Text.Split('^');
            txtPatientCity.Text = l_items[0].Replace("%CO",string.Empty);
            txtPatientFirstName.Text = l_items[1].Split('$')[0];
            txtPatientLastName.Text = l_items[1].Split('$')[1];
            txtPatientAddress1.Text = l_items[2];
            string l_birthDate = l_items[3].Split('=')[1].Split('?')[0];
            l_birthDate = l_birthDate.Substring(l_birthDate.Length-8,8);
            txtPatientBirthDate.Text = l_birthDate.Substring(4, 2) + "/" + l_birthDate.Substring(6, 2) + "/" + l_birthDate.Substring(0, 4);
            //txtPatientZip.Text = 
        }

        void gvFiles_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //double clicked 
            //find item and open in new window
            mmoss.orm.File l_item = ((mmoss.orm.File)gvFiles.Rows[gvFiles.SelectedCells[0].RowIndex].DataBoundItem);
        }

        void dgPatientList_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            throw new NotImplementedException();
        }

        void tbPatient1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tbPatient1.SelectedTab == tabPage1)
            {
            }

            if (tbPatient1.SelectedTab == tabPage2)
            {
                if (_currentPatient == null) tbPatient1.SelectedTab = tabPage1;
            }
            if (tbPatient1.SelectedTab == tabPage3)
            {
                if (_currentPatient == null) tbPatient1.SelectedTab = tabPage1;
            }
            //new tab selected.  Need to know if a patient is selected before access is given
        }

        void dgPatientList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //bring up patient info
            loadPatient((Patient)dgPatientList.Rows[e.RowIndex].DataBoundItem);
        }

        void txtLicenseInfo_KeyUp(object sender, KeyEventArgs e)
        {
            //set a timer to wait for input
            if (((TextBox)sender).Text == "") return;
            string sLastChar = ((TextBox)sender).Text.Substring(((TextBox)sender).Text.Length - 1, 1);
            if (timer1.Enabled)
            {
                //keep timer going
                timer1.Stop();
                timer1.Start();
            }
            if (sLastChar=="%")
            {
                //begin TIMER
                timer1.Enabled = true;
                timer1.Start();
            }
            else if (sLastChar=="?")
            {
                //end character -- wait for tic to disable to stop timer and parse
            }
        }

        void chkMember_Click(object sender, EventArgs e)
        {
            //pnMember.Enabled = chkMember.Checked;
            dtDateMember.Text = string.Format("{0:d/M/yyyy}", DateTime.Now);
        }

        void txtPatientNameSearch_KeyUp(object sender, KeyEventArgs e)
        {
            List<Patient> l_searchResult = dbConn.db.Patients.Get(
            string.Empty
            , ((TextBox)sender).Text
            , string.Empty
            , string.Empty
            , null
            , null
            );
            dgPatientList.DataSource = l_searchResult;
        }

        void txtPatientNameSearch_KeyDown(object sender, KeyEventArgs e)
        {
        }

        private void txtMemberDate_TextChanged(object sender, EventArgs e)
        {

        }
        private void loadPatient(Patient l_patient)
        {
            _currentPatient = l_patient;
            txtPatientLastName.Text = l_patient.patientLastName;
            txtPatientFirstName.Text = l_patient.patientFirstName;
            txtPatientCity.Text = l_patient.patientCity;
            txtPatientAddress1.Text = l_patient.patientAddress;
            txtPatientAddress2.Text = l_patient.patientAddress2;
            dtDateMember.Text = l_patient.patientMemberDate.ToString();
            txtLicenseInfo.Text=l_patient.patientDriversLicenseString;
            txtPatientZip.Text = l_patient.patientZip;
            txtEmailAddress.Text = l_patient.patientEmailAddress;
            cboState.Text = l_patient.patientState;
            //fire off zip lookup
            //load files
            gvFiles.DataSource = l_patient.Files;

            //date items
            dtDateMember.Text = AppTools.formatDate(l_patient.patientMemberDate);
            dtDoctorDate.Text = AppTools.formatDate(l_patient.patientDatePhd);
            dtLicenseExp.Text = AppTools.formatDate(l_patient.patientDatePrescriptionExpiration);
            //dtReceiptDate.Text = (l_patient.dat.patientMemberDate.ToString() == "" ? "" : string.Format("{0:d/M/yyyy}", l_patient.patientMemberDate));
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            tbPatient1.SelectedIndex = 2;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                using (Stream l_File = openFileDialog1.OpenFile())
                {
                    if (l_File.Length > 0)
                    {
                        //save to db
                        mmoss.orm.File l_newfile = new orm.File();
                        FileType l_type = new FileType();
                        l_newfile.fileName = openFileDialog1.SafeFileName;
                        l_newfile.FileType = dbConn.db.FileTypes.Single(p => p.fileTypeID == openFileDialog1.FilterIndex);
                        l_newfile.fileSizeBytes = int.Parse(l_File.Length.ToString());
                        _currentPatient.Files.Add(l_newfile);
                        dbConn.db.SubmitChanges();
                        //upload the file to S3
                        s3upload.Upload(l_File, Default.CurrentLocation.Id);
                    }
                }

            }
        }

        private void btnAddNewPatient_Click(object sender, EventArgs e)
        {
            _currentPatient = null;
            _viewMode = viewMode.NEW;
            loadPatient(new Patient());
            txtLicenseInfo.Focus();
        }

        private void buildPatientByForm(Patient newPatient)
        {
            //Patient newPatient = new Patient();
            //build the base informaiton
            newPatient.patientAddress = txtPatientAddress1.Text;
            newPatient.patientAddress2 = txtPatientAddress2.Text;
            newPatient.patientCity = txtPatientCity.Text;
            newPatient.patientState = cboState.Text;
            newPatient.patientZip = txtPatientZip.Text;
            newPatient.patientFirstName = txtPatientFirstName.Text;
            newPatient.patientLastName = txtPatientLastName.Text;
            newPatient.patientEmailAddress = txtEmailAddress.Text;
            newPatient.patientDriversLicenseString = txtLicenseInfo.Text;

            //todo -- fill in member info

            //build additional info
            //newPatient.patientDateBirth = DateTime.Parse(txtpat
            //return newPatient;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            //save the data
            //insert the new patient, otherwise update
            if (_currentPatient == null)
            {
                Patient l_newPatient = new Patient();
                buildPatientByForm(l_newPatient);
                dbConn.db.Patients.InsertOnSubmit(l_newPatient);
                _currentPatient = l_newPatient;
            }
            else
            {
                buildPatientByForm(_currentPatient);
            }
            dbConn.db.SubmitChanges();
            //set the next tab
            tbPatient1.SelectedTab = tabPage2;
        }

        private void btnSaveMedInfo_Click(object sender, EventArgs e)
        {
            _currentPatient.patientDatePhd = DateTime.Parse(dtDoctorDate.Text);
            _currentPatient.patientDatePrescriptionExpiration = DateTime.Parse(dtLicenseExp.Text);
            _currentPatient.patientMemberDate = DateTime.Parse(dtDateMember.Text);
            _currentPatient.patientDateBirth = DateTime.Parse(txtPatientBirthDate.Text);
            //_currentPatient.patientMMCID=
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnPreview_Click_1(object sender, EventArgs e)
        {
            _viewMode = viewMode.PREVIEW;
            //init camera
            l_cam = new mmoss.tools.webcamera.WebCam();
            l_cam.Container = pictureBox1;
            
            //change tab
            tbPatient1.SelectedTab = tabPage3;
            
            //stream camera
            l_cam.OpenConnection();
        }

        private void btnCheckIn_Click(object sender, EventArgs e)
        {
            PatientCheckIn l_checkIn = new PatientCheckIn();
            l_checkIn.locationID=Default.CurrentLocation.Id;
            l_checkIn.User = Default.CurrentUser;
            l_checkIn.Patient = _currentPatient;
            dbConn.db.PatientCheckIns.InsertOnSubmit(l_checkIn);
            dbConn.db.SubmitChanges();
            //call event
            mmossEvents.raisePatient(_currentPatient);
            Default.LoggedInPatients.Add(_currentPatient);
            //close
            this.Close();

        }

    }
}

